#include "sys/socket.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "iostream"
#include "arpa/inet.h"
#include "unistd.h"

using namespace std;

int main(int argc, char **argv)
{
	struct sockaddr_in sin;
	int sockfd, client, ret;
	//char *buf = (char*)malloc(sizeof(char)* 64);
	char buf[64] = {0};

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd < 0){
		cout<<"error: socket()"<<endl;
		exit(1);
	}
	sin.sin_family = AF_INET;
	sin.sin_port = htons(9000);
	sin.sin_addr.s_addr = INADDR_ANY;

	int num = 1;
	ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void*)&num, sizeof     (int));

	//ret = inet_pton(AF_INET, INADDR_ANY, &(sin.sin_addr.s_addr));
	if(ret){
		cout<<"error: inet_pton()"<<endl;
		exit(1);
	}

	ret = bind(sockfd, (struct sockaddr*)&sin, sizeof(struct sockaddr));
	if(ret < 0){
		cout<<"error: bind()"<<endl;
		exit(1);
	}
cout<<"while"<<sizeof(buf)<<endl;
	while(1){
		ret = listen(sockfd, 32);
		if(ret < 0){
			cout<<"error: listen()"<<endl;
			exit(1);
		}
loop:
		client = accept(sockfd, NULL, NULL);
		if(client < 0){
			cout<<"error: accept()"<<endl;
			exit(1);
		}

		ret = read(client, buf, sizeof(buf));
		
		printf("messages: %s, %d\n", buf, ret);

		goto loop;
	}
		return 0;
}

